using BarManager.Core.ApplicationService.Interfaces;
using BarManager.Core.Entity;
using BarManager.UI.Web.HtmlHelpers;
using BarManager.UI.Web.Models;
using System.Linq;
using System.Web.Mvc;

namespace BarManager.UI.Web.Controllers
{
    [Authorize(Users = "admin")]
    public class ProductoController : BaseController<ProductoViewModel, Producto, int>
    {
        private ICategoriaService CategoriaService { get; set; }
        private IProveedorService ProveedorService { get; set; }

        public ProductoController(IProductoService service,
            ICategoriaService categoriaService, IProveedorService proveedorService)
            : base(service)
        {
            this.CategoriaService = categoriaService;
            this.ProveedorService = proveedorService;
        }

        public override ActionResult Index(int id = 0)
        {
            //- Creamos el modelo
            ProductoViewModel model = new ProductoViewModel
            {
                Categorias = CategoriaService.GetAll().OrderBy(x => x.Nombre),
                Proveedores = ProveedorService.GetAll().OrderBy(x => x.Nombre)
            };

            //- Buscamos el producto a modificar
            if (id > 0) model.Entity = Service.Get(x => x.Id == id);

            return View(model);
        }

        public override ActionResult List(string filter, int page = 1)
        {
            ProductoViewModel model = new ProductoViewModel
            {
                Entities = this.Service.Find(x => filter == null || x.Nombre.Contains(filter) || x.Categoria.Nombre.Contains(filter))
                                        .OrderBy(x => x.Nombre)
                                        .Skip((page - 1) * PageSize)
                                        .Take(PageSize),
                PagingInfo = new PagingInfo
                {
                    CurrentPage = page,
                    ItemsPerPage = PageSize,
                    TotalItems = this.Service.Find(x => filter == null || x.Nombre.Contains(filter) || x.Categoria.Nombre.Contains(filter))
                                              .Count()
                }
            };
            model.Filter = filter;            
            return View(model);
        }

        public override ActionResult Save(ProductoViewModel model)
        {
            //- Cargamos combo categorias
            if (model.Categorias == null) model.Categorias = CategoriaService.GetAll().OrderBy(x => x.Nombre);

            //- Cargamos combo proveedores
            if (model.Proveedores == null) model.Proveedores = ProveedorService.GetAll().OrderBy(x => x.Nombre);

            //- Guardamos o actualizamos
            if (model.Entity.Id > 0)
                ErrorList = this.Service.Update(model.Entity);
            else
                ErrorList = this.Service.Add(model.Entity);

            return ShowError(model, ErrorList);
        }
    }
}
